<script lang="ts" setup>
import {computed, onMounted, onUnmounted, onUpdated, ref, reactive} from 'vue'
import {NBadge, NImage} from 'naive-ui'
import MarkdownIt from 'markdown-it'
import mdKatex from '@traptitech/markdown-it-katex'
import mila from 'markdown-it-link-attributes'
import hljs from 'highlight.js'
import {useBasicLayout} from '@/hooks/useBasicLayout'
import {t} from '@/locales'
import {copyToClip} from '@/utils/copy'

// 确保引入MathJax
// import {mathjax} from 'mathjax-full/js/mathjax.js';
// import {TeX} from 'mathjax-full/js/input/tex.js';
// import {SVG} from 'mathjax-full/js/output/svg.js';
// import {liteAdaptor} from 'mathjax-full/js/adaptors/liteAdaptor.js';
// import {RegisterHTMLHandler} from 'mathjax-full/js/handlers/html.js';
// import {AllPackages} from 'mathjax-full/js/input/tex/AllPackages.js';

// // 创建适配器和文档处理器
// const adaptor = liteAdaptor();
// RegisterHTMLHandler(adaptor);


const state = reactive({
	user: "",
	html: "",
	img: "",
})
// 配置MathJax
// const tex = new TeX({packages: AllPackages});
// const svg = new SVG({fontCache: 'none'});
// const doc = mathjax.document('', {InputJax: tex, OutputJax: svg});

// // 用于渲染数学公式的函数
// function renderMath(math: any) {
// 	return adaptor.outerHTML(doc.convert(math, {display: true}));
// }

interface Props {
	inversion?: boolean;
	error?: boolean
	text?: string
	loading?: boolean
	asRawText?: boolean;
	text_src?: string
	latex_src?: string
}


const props = defineProps<Props>()

const {isMobile} = useBasicLayout()

const textRef = ref<HTMLElement>()

const mdi = new MarkdownIt({
	html: false,
	linkify: true,
	highlight(code, language) {
		const validLang = !!(language && hljs.getLanguage(language))
		if (validLang) {
			const lang = language ?? ''
			return highlightBlock(hljs.highlight(code, {language: lang}).value, lang)
		}
		return highlightBlock(hljs.highlightAuto(code).value, '')
	},
})

mdi.use(mila, {attrs: {target: '_blank', rel: 'noopener'}})
mdi.use(mdKatex, {blockClass: 'katexmath-block rounded-md p-[10px]', errorColor: ' #cc0000'})

const wrapClass = computed(() => {
	return [
		'text-wrap',
		'min-w-[20px]',
		'rounded-md',
		isMobile.value ? 'p-2' : 'px-3 py-2',
		props.inversion ? 'bg-[#d2f9d1]' : 'bg-[#f4f6f8]',
		props.inversion ? 'dark:bg-[#a1dc95]' : 'dark:bg-[#1e1e20]',
		props.inversion ? 'message-request' : 'message-reply',
		{'text-red-500': props.error},
	]
})
const text = computed(() => {
	const value = props.text ?? ''
	if (!props.asRawText) {
		return mdi.render(value)
	} else {
		return value
	}
})

const text_src = props.text_src
const latex_src = props.latex_src

function highlightBlock(str: string, lang?: string) {
	return `<pre class="code-block-wrapper"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><span class="code-block-header__copy">${t('chat.copyCode')}</span></div><code class="hljs code-block-body ${lang}">${str}</code></pre>`
}

function addCopyEvents() {
	if (textRef.value) {
		const copyBtn = textRef.value.querySelectorAll('.code-block-header__copy')
		copyBtn.forEach((btn) => {
			btn.addEventListener('click', () => {
				const code = btn.parentElement?.nextElementSibling?.textContent
				if (code) {
					copyToClip(code).then(() => {
						btn.textContent = '复制成功'
						setTimeout(() => {
							btn.textContent = '复制代码'
						}, 1000)
					})
				}
			})
		})
	}
}

// const sssa = () => {
// 	state.html = renderMath("1")
// }

function removeCopyEvents() {
	if (textRef.value) {
		const copyBtn = textRef.value.querySelectorAll('.code-block-header__copy')
		copyBtn.forEach((btn) => {
			btn.removeEventListener('click', () => {
			})
		})
	}
}

onMounted(() => {
	if (localStorage.getItem("room_id")) {
		state.user = localStorage.getItem("room_id") || ""
	}
	addCopyEvents()
})

onUpdated(() => {
	addCopyEvents()
})

onUnmounted(() => {
	removeCopyEvents()
})
</script>

<template>
	<div :class="wrapClass">
		<div ref="textRef" class="leading-relaxed break-words">
			<div v-if="!inversion">
				<p class="math-container" v-html="state.html"></p>
				<n-space class="math-container">
					<div v-if="state.user" style="font-weight: bold">当前房间 :
						<n-badge type="success">
							<template #default>
								<span>{{ state.user }}房</span>
							</template>
						</n-badge>
					</div>
					<n-badge v-else type="warning">
						<template #default>
							<span>数模神器 5.0 version</span>
						</template>
					</n-badge>
					<br>
					<n-image
						v-if="text_src!='http://106.53.97.117:7777/static/null'"
						style="width:20%;padding: 20px 0"
						:src=text_src
					/>
					<n-image
						v-if="latex_src!='null'"
						style="width:20%;padding: 20px 5px"
						:src=latex_src
					/>
				</n-space>
				<hr>
				<div v-if="!asRawText" style="padding-top: 5px" class="markdown-body" v-html="text"/>
				<div v-else class="whitespace-pre-wrap" v-text="text"/>
			</div>
			<div v-else class="whitespace-pre-wrap" v-text="text"/>
			<template v-if="loading">
				<span class="dark:text-white w-[4px] h-[20px] block animate-blink"/>
			</template>
		</div>
	</div>
</template>

<style lang="less">
@import url(./style.less);
</style>
